/**
 * Created by yujianfu on 2016/11/23.
 */
import React, {Component, PropTypes} from 'react'
import {Card, Radio, Button, Popconfirm, message} from 'antd'
import {sortable} from 'react-sortable'
import Styles from './Index.less'
import Add from './Add'
import {fetchPost} from './../../../utils/request'

const RadioButton = Radio.Button
const RadioGroup = Radio.Group

class Index extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      effective: '0',
      reload: false,
      orderChanged: false,
      sortableListItem: null,
      draggingIndex: null,

      data: {
        items: null
      },
      page: {
        pageSize: 15,
        totalNum: 0,
        pageNum: 1
      },
      params: [],
      sortData: {
        originIds: [],
        sortedIds: []
      }
    }
  }

  onchange(current) {
    this.setState({
      page: {
        ...this.state.page,
        pageNum: current
      }
    }, () => {
      this.getData()
    })
  }

  componentDidMount() {
    this.getSortableData()
  }

  getSortableData() {
    var self = this
    let ListItem = React.createClass({
      displayName: 'SortableListItem',
      removeActivity (serialNum) {
        fetchPost(`/cms/activity/${serialNum}/down`, {}).then(res => {
          if (res.code === 0) {
            message.success('The activity was successfully removed!');
            this.props.children.refreshData()
          } else {
            message.error(res.msg)
          }
        });
      },
      render: function () {
        console.log(this.props, 'ef')
        return (
          <div {...this.props} className={Styles.item}>
            <Card noHovering={true}>
              <div className={Styles.itemContent}>
                <img src={this.props.children.imageUrl}/>
              </div>
              <div className={Styles.itemContent} style={{width: '63%'}}>
                <p>SerialNum: {this.props.children.serialNum}</p>
                <p>
                  Title: {this.props.children.title}
                </p>
                <p>
                  Body: {this.props.children.body}
                </p>
                <p>
                  Activity Url: {this.props.children.activityUrl}
                </p>
                <p>
                  Create Time: {this.props.children.gmtCreate}
                </p>
              </div>
              <div className={Styles.itemContent} style={{width: '10%', float: 'right'}}>
                {
                  this.props.children.effective === '2' ?
                    <Popconfirm placement="top" title={'Confirm down？'} onConfirm={() => {
                      this.removeActivity(this.props.children.serialNum)
                    }}
                                okText="Ok"
                                cancelText="Cancel">
                      <Button type="primary" style={{float: 'right'}}>
                        Down
                      </Button>
                    </Popconfirm>
                    :
                    this.props.children.effective === '4' ?
                      <Button type="dashed" disabled style={{float: 'right'}}>
                        Has been down
                      </Button>
                      :
                      this.props.children.effective === '3' ?
                        <Button type="dashed" disabled style={{float: 'right'}}>
                          Processing failure
                        </Button>
                        :
                        <span></span>
                }
              </div>
            </Card>
          </div>
        )
      }
    })

    this.setState({
      sortableListItem: sortable(ListItem)
    }, () => {
      this.getData()
    })
  }

  getData() {
    fetchPost(`/cms/activity/${this.state.effective}/list`, {}).then(json => {
      if (json.data != null) {
        var data = json.data.itemList
        var ids = []
        data.map(function (item) {
          ids.push(item.serialNum)
        })

        this.setState({
          data: {
            items: data
          },
          sortData: {
            ...this.state.sortData,
            originIds: ids
          }
        })
      }
    })
  }

  updateState(obj) {
    console.log(obj, 'obj')
    if (obj.draggingIndex != null) {
      var sortedIds = []
      if (typeof(obj.items) != 'undefined') {
        obj.items.map(function (item) {
          sortedIds.push(item.serialNum)
        })
      }

      this.setState({
        orderChanged: true,
        draggingIndex: obj.draggingIndex,
        sortData: {
          ...this.state.sortData,
          sortedIds: sortedIds
        }
      }, () => {
        console.log(this.state)
      })
    }
  }

  reload() {
    this.getData()
  }

  changeParams(params) {
    this.getData()
  }

  render() {
    var self = this
    let listItems = null
    if (this.state.sortableListItem != null && this.state.data.items != null) {
      let SortableListItem = this.state.sortableListItem
      console.log(this.state.effective, 'ef2')
      listItems = this.state.data.items.map((item, i) => {
        return (
          <SortableListItem
            key={i}
            updateState={(e) => this.updateState(e)}
            items={this.state.data.items}
            draggingIndex={this.state.draggingIndex}
            sortId={i}
            outline="list"
            childProps={() => {
              this.getData()
            }}
          >{{
            ...item, effective: this.state.effective, refreshData: () => {
              this.getData()
            }
          }}</SortableListItem>
        )
      }, this)
    } else {
      listItems = (<div></div>)
    }

    return (
      <div style={{width: '70%'}}>

        <div style={{'marginTop': 20, width: '80%', display: 'inline-block'}}>
          <Add changeParams={() => this.changeParams()}/>
        </div>
        <div className="mt20 pl10">
          <RadioGroup onChange={(e) => {
            console.log(e, 'onChange')
            this.setState({
              effective: e.target.value
            }, () => {
              this.getData()
            })
          }} defaultValue="0">
            <RadioButton value="0">To Be Processed</RadioButton>
            <RadioButton value="1">In The Processing</RadioButton>
            <RadioButton value="2">Processing Success</RadioButton>
            <RadioButton value="3">Processing Failure</RadioButton>
            <RadioButton value="4">Has Been Down</RadioButton>
          </RadioGroup>
        </div>
        <div style={{'marginTop': 10, width: '100%'}}>
          {listItems}
        </div>

      </div>
    )
  }
}

export default Index
